package com.ias.agdis_r.manager;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.ias.agdis_r.action.bill.BillResponseAction;
import com.ias.agdis_r.action.flight.FlightResponseAction;
import com.ias.agdis_r.action.security.SecurityResponseAction;
import com.ias.agdis_r.action.subscribe.SubscribeResponseAction;
import com.ias.agdis_r.action.task.TaskResponseAction;
import com.ias.agdis_r.activity.BoxActivity;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponseHeader;
import com.ias.agdis_r.util.S;

import java.util.List;

public class ActionManager {

	private static ActionManager instance = null;// 单例的数据库管理器

	/** 更新UI事件 */
	public static final int UI_UPDATE = 0;
	/** 更新UI事件 */
	public static final int UI_RESPONSE_SUCESS = 1;
	/** 更新UI事件 */
	public static final int UI_RESPONSE_FAIL = 2;
	/** 显示进度条事件 */
	
	public static final int UI_SHOW_PROGRESS = 3;
	/** 隐藏进度条事件 */
	public static final int UI_HIDE_PROGRESS = 4;
	/** 刷新消息盒子事件 */
	public static final int UI_REFRESH_BOX = 5;
	
	public static final int UI_SHOW_DIALOG_DOWNLOAD = 6;

	/** 航班相关消息返回结果处理类 */
	private FlightResponseAction flightResponseAction = null;
	/** 登录/登出消息返回结果处理类 */
	private SecurityResponseAction securityResponseAction = null;
	/** 任务相关消息返回结果处理类 */
	private TaskResponseAction taskResponseAction = null;
	/** 单据相关消息返回结果处理类 */
	private BillResponseAction billResponseAction = null;
	/** 订阅相关消息返回结果处理类 */
	private SubscribeResponseAction subscribeResponseAction = null;

	public ActionManager() {
		flightResponseAction = new FlightResponseAction();
		securityResponseAction = new SecurityResponseAction();
		taskResponseAction = new TaskResponseAction();
		billResponseAction = new BillResponseAction();
	}

	/**
	 * 单例模式
	 * 
	 * @return
	 */
	public static ActionManager getInstance() {
		// TODO Auto-generated method stub
		if (instance == null) {
			instance = new ActionManager();
		}
		return instance;
	}

	/**
	 * 获取登录操作类
	 * @return
	 */
	public SecurityResponseAction getSecurityResponseAction(){
		return securityResponseAction;
	}

	/**
	 * 处理Response返回消息
	 * 
	 * @param serviceId
	 * @param response
	 */
	public void handleResponse(String serviceId, BaseResponse response) {
		if (S.isEmpty(serviceId)||response == null ||response.getHeader() == null) {
			return;
		}

		if (response.getHeader().getStatus() == BaseResponseHeader.STATUS_SUCCESS) // 发送消息返回的状态值如果是成功
		{
			if (serviceId.equals(MessageModel.QFIQ)) {
				flightResponseAction.receiveQFIQ(response);
			}
			// 如果是未登录状态
			if (!ServiceManage.getInstance().getIsLogon()) {
				if (serviceId.equals(MessageModel.RELI)) {
					securityResponseAction.receiveRELI(response);
				}
			}
			// 如果是登录状态，才处理以下消息
			else {
				if (serviceId.equals(MessageModel.RELO)) {
					securityResponseAction.receiveRELO(response);
				} else if (serviceId.equals(MessageModel.TMRP)) {
					taskResponseAction.receiveTMRP(response);
				} else if (serviceId.equals(MessageModel.TTRQ)) {
					taskResponseAction.receiveTTRQ(response);
				} else if (serviceId.equals(MessageModel.TRPT)) {
					taskResponseAction.receiveTRPT(response);
				} else if (serviceId.equals(MessageModel.FLG4)) {
					taskResponseAction.receiveFLG4(response);
					return;
				} else if (serviceId.equals(MessageModel.FLG41)) {
					taskResponseAction.receiveFLG41(response);
					return;
				} else if (serviceId.equals(MessageModel.FLG1)) {
					taskResponseAction.receiveFLG1(response);
					return;
				} else if (serviceId.equals(MessageModel.TASK)) {
					taskResponseAction.receiveTask(response);
				} else if (serviceId.equals(MessageModel.TRBD)) {
					taskResponseAction.receiveTRBD(response);
				} else if (serviceId.equals(MessageModel.BLRQ)) {
					billResponseAction.receiveBLRQ(response);
				} else if (serviceId.equals(MessageModel.BLDT)) {
					billResponseAction.receiveBLDT(response);
				} else if (serviceId.equals(MessageModel.BLPT)) {
					billResponseAction.receiveBLPT(response);
				} else if (serviceId.equals(MessageModel.TTAQ)) {
					subscribeResponseAction.receiveTTAQ(response);
				} else if (serviceId.equals(MessageModel.HBDY)) {
					subscribeResponseAction.receiveHBDY(response);
				} else if(serviceId.equals(MessageModel.DYMB)){
					securityResponseAction.receiveDYMB(response);
					return;
				} else if (serviceId.equals(MessageModel.QQRY)){
					taskResponseAction.receiveQQRY(response);
				} else if (serviceId.equals(MessageModel.TTAS)){
					taskResponseAction.receiveTTAS(response);
				} else if (serviceId.equals(MessageModel.TTAL)){
					taskResponseAction.receiveTTAL(response);
				} else if (serviceId.equals(MessageModel.UCBD)){
					taskResponseAction.receiveUCBD(response);
				} else if (serviceId.equals(MessageModel.FLG10)){
					taskResponseAction.receiveFLG10(response);
				} else if (serviceId.equals(MessageModel.QQRY)){
					taskResponseAction.receiveQQRY(response);
				} else if (serviceId.equals(MessageModel.GHOU)){
					taskResponseAction.receiveGHOU(response);
				} else if (serviceId.equals(MessageModel.GTFL)){
					taskResponseAction.receiveGTFL(response);
				} else if (serviceId.equals(MessageModel.ULBC)) {
					taskResponseAction.receiveULBC(response);
				} else if (serviceId.equals(MessageModel.DLBC)) {
					taskResponseAction.receiveDLBC(response);
				} else if (serviceId.equals(MessageModel.QLBC)) {
					taskResponseAction.receiveQLBC(response);
				} else if (serviceId.equals(MessageModel.WGLM)) {
					taskResponseAction.receiveWGLM(response);
				} else if (serviceId.equals(MessageModel.WGAM)) {
					taskResponseAction.receiveWGAM(response);
				} else if (serviceId.equals(MessageModel.WGDM)) {
					taskResponseAction.receiveWGDM(response);
				} else if (serviceId.equals(MessageModel.FXLI)) {
					taskResponseAction.receiveFXLI(response);
				} else if (serviceId.equals(MessageModel.FXLR)) {
					taskResponseAction.receiveFXLR(response);
				}
			}
			// 请求成功UI处理
			responseSuccess(serviceId, response);
		}
		//如果用户的状态为非登录
		else if(response.getHeader().getStatus() == BaseResponseHeader.STATUS_FAILED){
			
			if(S.isNotEmpty(response.getHeader().getErrorCode())&&response.getHeader().getErrorCode().equals(BaseResponseHeader.ERRORCODE_UNLOGIN))
			{
				//注销
				ServiceManage.getInstance().onLogonOut();
				EffectManager.getInstance().vibrate();
				EffectManager.getInstance().playSound(ParameterModel.MUSIC_EFFECT_USER_OFFLINE);
				S.startActivity(MainActivity.class);
//				EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK,
//						DataBaseManager.getInstance().getContext().getString(R.string.request_err_unlogin), false);
//				//跳转到登录页面
//				ServiceManage.getInstance().startLoginActivity();
			}
			// 摘要、新任务、未完成任务请求失败不调用回调方法
			else if (serviceId.equals(MessageModel.BLRQ)
					|| serviceId.equals(MessageModel.FLG3)
					|| serviceId.equals(MessageModel.FLG1)
					|| serviceId.equals(MessageModel.TASK)) {
				return;
			} else {
				// 请求失败UI处理
				responseFail(serviceId, response);
			}
		}

	}

	/**
	 * 隐藏restful请求进度条
	 */
	public void hideProgress() {
		Handler handler = DataBaseManager.getInstance().getUIHandler();
		if (handler != null) {
			Message msg = handler.obtainMessage(ActionManager.UI_HIDE_PROGRESS);
			handler.sendMessage(msg);
		}
	}

	/**
	 * 显示restful请求进度条
	 */
	public void showProgress() {
		Handler handler = DataBaseManager.getInstance().getUIHandler();
		if (handler != null) {
			Message msg = handler.obtainMessage(ActionManager.UI_SHOW_PROGRESS);
			handler.sendMessage(msg);
		}
	}

	/**
	 * 显示更新版本，下载的提示框
	 */
	public void showDialogDownLoad(){
		
		Handler handler = DataBaseManager.getInstance().getUIHandler();
		if (handler != null) {
			Message msg = handler.obtainMessage(ActionManager.UI_SHOW_DIALOG_DOWNLOAD);
			handler.sendMessage(msg);
		}
	}
	/**
	 * 刷新UI
	 */
	public void responseSuccess(String serviceId, BaseResponse response) {
		Handler handler = DataBaseManager.getInstance().getUIHandler();
		if (handler != null) {
			Message msg = handler
					.obtainMessage(ActionManager.UI_RESPONSE_SUCESS);
			Bundle bundle = new Bundle();
			bundle.putString("serviceId", serviceId);
			bundle.putSerializable("response", response);
			msg.setData(bundle);
			handler.sendMessage(msg);
		}
	}

	/**
	 * 刷新UI
	 */
	public void responseFail(String serviceId, BaseResponse response) {
		Handler handler = DataBaseManager.getInstance().getUIHandler();
		if (handler != null) {
			Message msg = handler.obtainMessage(ActionManager.UI_RESPONSE_FAIL);
			Bundle bundle = new Bundle();
			bundle.putString("serviceId", serviceId);
			bundle.putSerializable("response", response);
			msg.setData(bundle);
			handler.sendMessage(msg);
		}
	}

	/**
	 * 刷新UI
	 */
	public void updateUI(String serviceId) {
		Handler handler = DataBaseManager.getInstance().getUIHandler();
		if (handler != null) {
			Message msg = handler.obtainMessage(ActionManager.UI_UPDATE);
			Bundle bundle = new Bundle();
			bundle.putString("serviceId", serviceId);
			msg.setData(bundle);
			handler.sendMessage(msg);
		}
	}
	
	/**
	 * 刷新UI
	 */
	public void updateUI(String serviceId,String tnb) {
		Handler handler = DataBaseManager.getInstance().getUIHandler();
		if (handler != null) {
			Message msg = handler.obtainMessage(ActionManager.UI_UPDATE);
			Bundle bundle = new Bundle();
			bundle.putString("serviceId", serviceId);
			bundle.putString(MessageModel.TNB, tnb);
			msg.setData(bundle);
			handler.sendMessage(msg);
		}
	}


    /**
     * 刷新消息盒子
     */
    public void refreshBox(String boxType) {
        Handler handler = DataBaseManager.getInstance().getUIHandler();
        if (handler != null) {
            Message msg = handler.obtainMessage(ActionManager.UI_REFRESH_BOX);
            handler.sendMessage(msg);
            //1.如果不是注销
			//2.如果当前是消息盒子弹出模式
			//3.如果当前显示的页面不是BoxActivity
			//弹出消息盒子
            if(!MessageModel.REFRESH_BOXCLEAN.equals(boxType)&&
					ParameterModel.isBoxPopMode){
				Context context = DataBaseManager.getInstance().getContext();
				//如果当前Activity不存在
            	if(DataBaseManager.getInstance().getBoxActivty()!=null) {
					//如果当前Activity不可见
            		if(!isForeground(context,BoxActivity.class.getName())) {
						Activity activity = DataBaseManager.getInstance().getBoxActivty();
						activity.finish();
						//启动消息盒子
						Intent intent = new Intent(context,
								BoxActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.putExtra(MessageModel.REFRESH_BOX_TYPE, boxType);
						context.startActivity(intent);
					}
				}else{
					//启动消息盒子
					Intent intent = new Intent(context,
							BoxActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.putExtra(MessageModel.REFRESH_BOX_TYPE, boxType);
					context.startActivity(intent);
				}
			}
        }
    }

	public boolean  isForeground(Context context, String className) {
		if (context == null || S.isEmpty(className)) {
			return false;
		}

		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
		if (list != null && list.size() > 0) {
			ComponentName cpn = list.get(0).topActivity;
			if (className.equals(cpn.getClassName())) {
				return true;
			}
		}
		return false;
	}
}
